package Chinese.Education.Identify.service;

import Chinese.Education.Identify.mapper.TeacherUserMapper;
import Chinese.Education.Identify.pojo.TeacherUser;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class TeacherUserService {
    @Resource
    private TeacherUserMapper teacherUserMapper;

    public Map<String, Object> login(TeacherUser user, HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        TeacherUser teacherUser = teacherUserMapper.login(user.getUsername());
        System.out.println("尝试登录的用户名: " + user.getUsername());
        System.out.println("查询结果: " + teacherUser);

        // 用户名不存在
        if(teacherUser == null) {
            map.put("code", 901);
            map.put("msg", "用户名不存在");
            return map;
        }

        // 密码验证
        String password = user.getPassword();
        // 密码加密两次
        String password_md5 = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        String password_md5_02 = DigestUtils.md5DigestAsHex(password_md5.getBytes(StandardCharsets.UTF_8));

        // 数据库中的密码
        String dbPassword = teacherUser.getPassword();

        if(!dbPassword.equals(password_md5_02)) {
            map.put("code", 902);
            map.put("msg", "对不起，密码错误");
            return map;
        }

        // 登录成功
        map.put("code", 200);
        map.put("msg", "登录成功");
        request.getSession().setAttribute("user", user); // 如果用户登录成功，则在session存放一个当前用户的信息，作为拦截比对内容
        return map;
    }



}
